﻿using System.Collections.Generic;
using System.Linq;
using Abp.AutoMapper;
using Hicap.AuthorizationServer.Application.Dto;
using Hicap.AuthorizationServer.Core.Managers;
using Hicap.AuthorizationServer.Core.Models;
using Microsoft.EntityFrameworkCore;

namespace Hicap.AuthorizationServer.Application.Sys
{
    public class AuthObjectAppService : AuthorizationServerApplicationBase<AuthObject, AuthObjectListDto, AuthObjectEditDto>
    {
        private readonly IAuthObjectManager _manager;

        public AuthObjectAppService(IAuthObjectManager manager) : base(manager)
        {
            _manager = manager;
        }

        public List<AuthObjectTreeDto> GetAuthObjectTree()
        {
            var alllist = GetQuery(_manager.GetQuery(null)).Include(x => x.ParentObject).ToList();

            var rootlist = alllist.Where(x => x.ParentObject == null);
            var resultList = new List<AuthObjectTreeDto>();

            foreach (var item in rootlist)
            {
                var result = new AuthObjectTreeDto
                {
                    CurrentNode = item.MapTo<AuthObjectListDto>(),
                    Childs = GetAuthObjectSubTree(item, alllist)
                };
                resultList.Add(result);
            }

            List<AuthObjectTreeDto> GetAuthObjectSubTree(AuthObject node, List<AuthObject> leafs)
            {
                var subtree = leafs.Where(x => x.ParentObject != null && x.ParentObject.Id == node.Id);
                var subResult = new List<AuthObjectTreeDto>();
                foreach (var authObject in subtree)
                {
                    subResult.Add(new AuthObjectTreeDto()
                    {
                        CurrentNode = authObject.MapTo<AuthObjectListDto>(),
                        Childs = GetAuthObjectSubTree(authObject, leafs)
                    });
                }
                return subResult;
            }

            return resultList;
        }
    }
}